import React,{Component} from 'react';
import { Table, message, Modal } from 'antd';
import './index.less';
import axios from 'axios';
import echarts from 'echarts';
import Bread from '../common/Bread/index';
import {connect} from 'react-redux';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'


class ControlPanel extends React.Component {
	  constructor(props) {
			super(props);
			this.state = {
				toggleName: '展开',
				disabled: 'hide',
				blockName: 0,
				nodeName: 0,
				transactionName: 0,
				IntelligenceName: 0,
  		        data: [],
  		        onOff: true,
  		        transactionData: [],
  		        visible: false,
  		        ChannelId: '',
  		        Organization: '',
  		        TransactionId: '',
  		        TransactionTime: new Date().getTime(),
  		        User: '',
		  	}
	  	}
	  	
	  toggle =()=> {
	    if(this.state.toggleName == '展开'){
    		this.setState({
    			toggleName: '关闭',
    			disabled: '',
    		})
    	}else {
    		this.setState({
    			toggleName: '展开',
    			disabled: 'hide',
    		})
    	}
    }
	      
    clickNode = (name) => {  
      // alert(name+'--的值：');
      if(name.indexOf("网络") > -1){
      	// this.props.history.push('/net');
      }
    } 

    getData =()=>{
    	
    	setTimeout(()=>{
    		this.props.channelId;
    		this.props.changeNetwork;
    		this.props.changeOrgid;
			// console.log(this.props.ChannelId)
		})
    }

    componentWillUpdate(nextProps){
			// console.log(nextProps.changeNetwork)
            // console.log('11111 ' + this.props.changeNetwork)
        if(nextProps.changeNetwork !== this.props.changeNetwork){
            this.setState({
                transactionData: []
            })
        }
    	if(nextProps.channelId && nextProps.changeOrgid){
            // console.log(nextProps.changeNetwork)
			const sandbox = localStorage.getItem("sandbox");
			// console.log(sandbox,1000000,'sandbox')
            const queryChannelInfo = (!sandbox || sandbox == 0) ? '/api/sandbox/public/queryChannelInfo' : '/api/block/public/queryChannelInfo';
            const queryAllPeer = (!sandbox || sandbox == 0) ? '/api/sandbox/public/queryAllPeer' : '/api/block/public/queryAllPeer';
            const queryTransactionCount = (!sandbox || sandbox == 0) ? '/api/sandbox/public/queryTransactionCount' : '/api/block/public/queryTransactionCount';
            const chainCodeCount = (!sandbox || sandbox == 0) ? '/api/sandbox/fabric/queryChainCodeCount' : '/api/block/public/queryChainCodeCount';
            // console.log(sandbox, chainCodeCount)
    		setTimeout(()=>{
	    		if(this.state.onOff){
	    			this.setState({
	    				onOff: false
	    			},()=>{
                        // console.log(1)
	    				this.requestAjaxFn(queryChannelInfo, 'QueryChannelInfoReq', 0);
					    this.requestAjaxFn(queryAllPeer, 'QueryAllPeerReq', 1);
					    this.requestAjaxFn(queryTransactionCount, 'QueryTransactionCountReq', 2);
					    this.requestAjaxFn(chainCodeCount, 'QueryInstalledChainCodesReq', 3);
	    			})
	    		}
			})
			// console.log(1.5, this.props.changeOrgid, nextProps.changeOrgid, nextProps.changeNetwork, this.props.changeNetwork);
			if (!this.state.onOff && (nextProps.changeOrgid != this.props.changeOrgid || nextProps.changeNetwork != this.props.changeNetwork)) {
				// console.log(2);
				this.getData();
				setTimeout(() => {
					this.requestAjaxFn(queryChannelInfo, "QueryChannelInfoReq", 0);
					this.requestAjaxFn(queryAllPeer, "QueryAllPeerReq", 1);
					this.requestAjaxFn(queryTransactionCount, "QueryTransactionCountReq", 2);
					this.requestAjaxFn(chainCodeCount, "QueryInstalledChainCodesReq", 3);
				});
		    }
            
    	}
    }

    componentWillMount(){
    	this.getData();
	    //网络树接口
	    const _this = this;
	    const Token = localStorage.getItem("token");
	    axios({
	    	method: 'get',
	    	url: '/api/block/user/queryUserOrgNetworkTree',
	    	headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
	   	})
	    .then(function(response){
	    	_this.setState({
	    		data: JSON.parse(response.data.data)
	    	},()=>{
                _this.loadingNetWorkTree();
            })
	    	// console.log(_this.state.height);
	    })
	    .catch(function(error){
	    	console.log(error)
	    });
    }

    
    loadingNetWorkTree(){
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));
        // 绘制图表
        var _this = this;
        // console.log(this.state.data)
        // console.log(this.state.data.children)

        echarts.util.each(this.state.data.children, function (datum, index) {
           index % 2 === 0 && (datum.collapsed = true);
       });
        myChart.setOption(
            {
            tooltip: {
                trigger: 'item',
                triggerOn: 'mousemove',
            },
            series: [
                {
                    type: 'tree',
                    orient: 'vertical', 
                    data: [this.state.data],

                    top: '10%',
                    left: '2%',
                    bottom: '30%',
                    right: '2%',

                    symbol: 'emptyCircle',
                    symbolSize: 5,

                    label: {
                        normal: {
                            position: 'top',
                            rotate: -90,
                            verticalAlign: 'middle',
                            align: 'right',
                            fontSize: 12,
                        }
                    },
                    calculable : true,
                    leaves: {
                        label: {
                            normal: {
                                position: 'bottom',
                                rotate: -90,
                                verticalAlign: 'middle',
                                align: 'left',
                            }
                        }
                    },
                    itemStyle : {
                      normal: {
                          borderWidth: 1,
                          color: "#73A6FF",
                          borderColor: "#0350CF",
                          lineStyle: {
                              type: 'solid',
                              color:'rgba(227,227,238,1)',
                              width: 1,
                          },
                      } 
                    },
                    // symbol: 'circle',
                    expandAndCollapse: true,
                    animationDuration: 550,
                    animationDurationUpdate: 750
                }
            ]
        });
        //4.树绑定事件  
        myChart.on('click', function(params) { 
          var name = params.data.name;//点击的节点的name  
          //调用点击事件 
          // console.log(name); 
          _this.clickNode(name);  
        }); 
    } 
    columns = [{
    	title: '交易哈希',
    	dataIndex: 'hash',
    	key: '交易哈希',
    	render: (text,record) => (
    		<span className="transactionClass" onClick={this.TransactionModal.bind(this,text)}>{text}</span>
    	)
      }, {
    	title: '时间戳',
    	dataIndex: 'transactionTime',
    	key: '时间戳',
    	render: (text,record) => (
    		<span>{this.timestampToTime(text)}</span>
    	)
    }];

    TransactionModal =(text)=>{
    	this.setState({
    		visible: true,
    		ChannelId: this.state.transactionData[0].ChannelId,
    		Organization: this.state.transactionData[0].Organization,
    		TransactionId: this.state.transactionData[0].hash,
    		TransactionTime: this.state.transactionData[0].transactionTime,
    		User: this.state.transactionData[0].User,
    	})
    }
    handleCancel =()=>{
    	this.setState({
    		visible: false,
    	})
    }
    //最新交易
    newTransaction =(url,data)=>{
    	const _this = this;
		const Token = localStorage.getItem("token");
    	axios({
    		method: 'post',
    		url: url,
    		data: data,
	    	headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
    	})
    	.then(function(response){
    		let transactionData = [];
    		const oData = JSON.parse(response.data.data);
    		// console.log(oData)
    		response.data && oData.BlockInfoList.forEach((e,i)=>{
    			transactionData.push({
    				key: i+'',
    				"hash": e.TransactionList[0].TransactionId,
    				"transactionTime": e.TransactionList[0].TransactionTime,
    				ChannelId: e.TransactionList[0].ChannelId,
    				Organization: e.TransactionList[0].Organization,
    				User: e.TransactionList[0].User
    			})
    		})
    		_this.setState({
    			transactionData: transactionData,
    		})
    	})
    	.catch(function(error){
    	})
    }

    timestampToTime =(timestamp)=> {
		var date = new Date(timestamp * 1000);
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var h = date.getHours() < 10 ? "0" + date.getHours() + ":": date.getHours() + ':';
        var m = date.getMinutes() < 10 ? "0" + date.getMinutes() + ":" : date.getMinutes() + ':';
        var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return Y + M + D + ' ' + h + m + s;
   }

    //公共方法
    requestAjaxFn =(url,data,num)=>{
        // console.log(this.props.changeNetwork)
        if(!this.props.changeNetwork){
            this.setState({
                blockName: 0,
                nodeName: 0,
                transactionName: 0,
                IntelligenceName: 0,
            })
            return false
        }
    	const _this = this;
    	const Token = localStorage.getItem("token");

		const ChannelId = this.props.channelId;
		const FabricFlag = this.props.changeNetwork;
		const orgId = this.props.changeOrgid;

		if(data == 'QueryInstalledChainCodesReq'){
			var queryInstalledData = {
				"RequestType": data,
				"ChannelId": ChannelId,
				"FabricFlag": FabricFlag,
				"OrgId": orgId
			};
		}else {
			var queryInstalledData = {
				"RequestType": data,
				"ChannelId": ChannelId,
				"FabricFlag": FabricFlag,
			};
		}
    	axios({
    		method: 'post',
    		url: url,
    		data: queryInstalledData,
	    	headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
    	})
    	.then(function(response){
    		// console.log(data)
    		const oData = JSON.parse(response.data.data);
    			if(num === 0){
    				if(response.data.code == 200){
    					_this.setState({
    						blockName: (oData.ChannelInfo.Heigth == 0) ? oData.ChannelInfo.Heigth : oData.ChannelInfo.Heigth - 1
    					},()=>{
                            var queryTransactionoData = {
                                "RequestType":"QueryBlockByNumReq",
                                "FabricFlag" : FabricFlag,
                                "ChannelId" : ChannelId,
                                "QueryBlockInfo": {
                                    "StartIndex": (oData.ChannelInfo.Heigth == 0) ? oData.ChannelInfo.Heigth : oData.ChannelInfo.Heigth - 1,
                                    "Count": 1,
                                    "QueryType": 1
                                }
                            }
                            const sandbox = localStorage.getItem("sandbox");
                            const queryBlock = (!sandbox || sandbox == 0) ? '/api/sandbox/public/queryBlock' : '/api/block/public/queryBlock';
    						_this.newTransaction(queryBlock,queryTransactionoData);
    					})
    				}
    			}else if (num === 1){
    				if(response.data.code == 200){
	    				_this.setState({
	    					nodeName: oData.PeerInfoList.length
	    				})
	    			}	
    			}else if(num === 2){
    				if(response.data.code == 200){
	    				_this.setState({
	    					transactionName: (oData.TransactionIdCount == 0) ? oData.TransactionIdCount : oData.TransactionIdCount - 1
	    				})
	    			}	
    			}else if(num === 3){
    				if(response.data.code == 200){
    					_this.setState({
	    					IntelligenceName: oData.chainCodeCount
	    				})
    				}
    			}
    	})
    	.catch(function(error){
    	}) 
    }

	render(){
		const { visible, blockName, nodeName, transactionName, IntelligenceName, TransactionTime } = this.state;
		return(
            <div style={{paddingTop: '1px'}}>
                <Bread bread={['控制面板',['控制面板','controlPanel']]}/>
    			<div className="controlPanel" style={{marginTop: '-20px'}}>
    				<div className="panel-hd" style={{ display: 'none'}}>
    					<p>区块链网络树 <span onClick={this.toggle}>{this.state.toggleName}</span></p>
    					<div className={this.state.disabled}>
    						<div id="main" style={{ width: 950, height: 500 }}></div>
    					</div>	
    				</div>
    				<div className="panel-bd">
    					<div className="Item">
    						<div className="panelItem">
    							<div className="BlockChainTop">
    								<img src={require("./img/block.png")} className="img1"/>
    							</div>
    							<p className="blockNumber">{blockName}</p>
    							<h3>区块</h3>
    						</div>
    						<div className="panelItem">
    							<div className="BlockChainTop">
    								<img src={require("./img/node.png")} className="img2"/>
    							</div>
    							<p className="blockNumber">{nodeName}</p>
    							<h3>节点</h3>
    						</div>
    						<div className="panelItem">
    							<div className="BlockChainTop">
    								<img src={require("./img/transaction.png")} className="img3"/>
    							</div>
    							<p className="blockNumber">{transactionName}</p>
    							<h3>交易</h3>
    						</div>
    						<div className="panelItem">
    							<div className="BlockChainTop">
    								<img src={require("./img/Intelligence.png")} className="img4"/>
    							</div>
    							<p className="blockNumber">{IntelligenceName}</p>
    							<h3>智能合约</h3>
    						</div>
    					</div>	
    				</div>
    				<div className="panel-ft">
    					<h3>最新交易</h3>
    					<Table 
    						columns={this.columns} 
    						dataSource={this.state.transactionData} 
    						bordered
    						pagination={false} />
    				</div>
    				<Modal
    					visible = {visible}
    					onCancel={this.handleCancel}
    					footer={[null]}
    					className="modal"
    				>
    					<div className="transactionModal">
    						<p><span>频道：</span>{this.state.ChannelId}</p>
    						<p><span>组织：</span>{this.state.Organization}</p>
    						<p><span>交易哈希：</span><em>{this.state.TransactionId}</em></p>
    						<p><span>交易时间：</span>{this.timestampToTime(TransactionTime)}</p>
    						<p><span>用户：</span>{this.state.User}</p>
    					</div>
    				</Modal>
    			</div>
            </div>	
			)
	}
}

export default connect((state) => {
    return { ...state };
  })(ControlPanel);

